package leetcode.L500;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EX15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        int len = nums.length;
        for(int k = 0;k<nums.length-2;k++){
            if(k>0&&nums[k]==nums[k-1]){
                continue;
            }
            int i = k+1;
            int j = len-1;
            while(i<j){
                if(nums[k]+nums[i]+nums[j]==0){
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[k]);
                    list.add(nums[i]);
                    list.add(nums[j]);
                    res.add(list);
                    i++;
                    j--;
                    while(nums[i]==nums[i-1]){
                        i++;
                    }
                    while(nums[j]==nums[j+1]){
                        j--;
                    }
                }else if(nums[k]+nums[i]+nums[j]<0){
                    i++;
                }else{
                    j--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        EX15 ex15 = new EX15();
        int[] in = {-1,0,1,2,-1,-4};
        ex15.threeSum(in);
    }
}
